package com.example.ytyproject.component;

import com.example.ytyproject.config.exception.AppException;
import com.example.ytyproject.entity.vo.MinioInfo;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * minio文件管理
 */

@Slf4j
@Component
public class MinioComponent {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioInfo minioInfo;

    /**
     * 上传文件
     * @param file 文件
     * @return 文件路径
     */
    public String uploadFile(MultipartFile file, String filePath){
        if (null == file || 0 == file.getSize()){
            throw new AppException("上传文件不能为空!");
        }
        try {
            //判断是否存在
            createBucket();
            //原文件名
            String originalFilename = file.getOriginalFilename();
            // 修改文件名称
            String fileName = filePath + UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.indexOf("."));
            minioClient.putObject(PutObjectArgs.builder().bucket(minioInfo.getBuckname())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).build());
            return minioInfo.getEndpoint() + "/" + minioInfo.getBuckname() + "/" + fileName;
        } catch (Exception e){
            log.error("上传失败::", e);
            throw new AppException("上传失败!");
        }
    }

    public void createBucket() throws Exception{
        //如果不存在就创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioInfo.getBuckname()).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioInfo.getBuckname()).build());
        }
    }

    /**
     * 通过字节流上传
     * @param imageFullPath
     * @param bucketName
     * @param imageData
     * @return
     */
    public String uploadImage(String imageFullPath,
                              String bucketName,
                              byte[] imageData){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
        try {
            //判断是否存在
            createBucket();
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
                    .stream(byteArrayInputStream,byteArrayInputStream.available(),-1)
                    .contentType(".jpg")
                    .build());
            return minioInfo.getEndpoint()+"/"+bucketName+"/"+imageFullPath;
        }catch (Exception e){
            log.error("上传失败：{}",e.getMessage());
        }
        log.error("msg","上传失败");
        return null;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param fileName
     * @return
     */
    public int removeFile(String bucketName,String fileName){
        try {
            //判断桶是否存在
            boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (res) {
                //删除文件
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
            }
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
            return 1;
        }
        System.out.println("删除文件成功");
        return 0;
    }

    /**
     * 下载文件
     * @param fileName
     * @param bucketName
     * @param response
     */
    public void fileDownload(String fileName,
                             String bucketName,
                             HttpServletResponse response) {

        InputStream inputStream   = null;
        OutputStream outputStream = null;
        try {
            if (StringUtils.isBlank(fileName)) {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                String data = "文件下载失败";
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
                return;
            }

            outputStream = response.getOutputStream();
            // 获取文件对象
            inputStream =minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            byte buf[] = new byte[1024];
            int length = 0;
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            System.out.println("下载成功");
            inputStream.close();
        } catch (Throwable ex) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件下载失败";
            try {
                OutputStream ps = response.getOutputStream();
                ps.write(data.getBytes("UTF-8"));
            }catch (IOException e){
                e.printStackTrace();
            }
        } finally {
            try {
                outputStream.close();
                if (inputStream != null) {
                    inputStream.close();
                }}catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
